package com.jokins.admin.vue.user.utils;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

public class FixedHashPasswordUtils {

    private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    private static final int LENGTH = 8;

    /**
     * 生成一个随机字符串
     *
     * @return 随机字符串
     */
    public static String generateRandomString() {
        Random random = new Random();
        StringBuilder sb = new StringBuilder(LENGTH);
        for (int i = 0; i < LENGTH; i++) {
            int index = random.nextInt(CHARACTERS.length());
            sb.append(CHARACTERS.charAt(index));
        }
        return sb.toString();
    }

    /**
     * 使用 SHA-256 对字符串进行固定哈希加密
     *
     * @param input 原始密码
     * @return 固定哈希值
     */
    public static String sha256Hash(String input) {
        if (input == null || input.isEmpty()) {
            throw new IllegalArgumentException("密码不能为空");
        }
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hash = digest.digest(input.getBytes(StandardCharsets.UTF_8));
            StringBuilder hexString = new StringBuilder();
            for (byte b : hash) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("加密算法不可用", e);
        }
    }

    /**
     * 比较两个加密后的密码是否一致
     *
     * @param hashedPassword1 加密后的密码1
     * @param hashedPassword2 加密后的密码2
     * @return 如果一致返回 true，否则返回 false
     */
    public static boolean compareHashedPasswords(String hashedPassword1, String hashedPassword2) {
        return hashedPassword1 != null && hashedPassword1.equals(hashedPassword2);
    }

    public static void main(String[] args) {
        String password = generateRandomString();
        String hashed1 = sha256Hash(password);
        String hashed2 = sha256Hash(password);

        System.out.println("密码: " + password);
        System.out.println("加密后的密码 1: " + hashed1);
        System.out.println("加密后的密码 2: " + hashed2);
        System.out.println("两次加密是否一致: " + compareHashedPasswords(hashed1, hashed2));
    }
}
